package com.mini.framework.record;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DefaultReader extends RecordReader {
	
	private static final int BYTE_BUFFER = 1024;
	
	public DefaultReader(String path){
		super(path);
	}
	
	@Override
	public Map<String,List<RecordObject>> read() {
		File file = new File(getPath());
		Map<String,List<RecordObject>> totalMap = new ConcurrentHashMap<String,List<RecordObject>>();
		List<Callable<Map<String,List<RecordObject>>>> calls = new ArrayList<Callable<Map<String,List<RecordObject>>>>();
		//目录.
		if(file.exists() && file.isDirectory()){
			File[] fs = file.listFiles();
			for(File f:fs){
				calls.add(new FileReadCallable(f));
			}
		}else{
			calls.add(new FileReadCallable(file));
		}
		ExecutorService exeSvc = Executors.newFixedThreadPool(calls.size());
		try{
			List<Future<Map<String,List<RecordObject>>>> futuers = exeSvc.invokeAll(calls);
			for (Future<Map<String,List<RecordObject>>> futuer : futuers){
				Map<String,List<RecordObject>> subMap = futuer.get();
				if(subMap != null){
					Iterator<String> it = subMap.keySet().iterator();
					while(it.hasNext()){
						String key = it.next();
						List<RecordObject> subList = subMap.get(key);
						totalMap.put(key, subList);
					}
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return totalMap;
	}
	
	
	private static class FileReadCallable implements Callable<Map<String,List<RecordObject>>>{
		
		private File file;
		
		private FileChannel fileChannel;
		
		private FileInputStream fileIn;
		
		public FileReadCallable(File file){
			this.file = file;
			try{
				
				fileIn = new FileInputStream(file);
				fileChannel = fileIn.getChannel();
				
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		

		@Override
		public Map<String,List<RecordObject>> call() throws Exception {
			
			StringBuilder sb = new StringBuilder();
			ByteBuffer byteBuffer = ByteBuffer.allocate(BYTE_BUFFER);
			
			while (fileChannel.read(byteBuffer) != -1) {
				byteBuffer.flip();
				while (byteBuffer.hasRemaining()) {
					sb.append((char) byteBuffer.get());
				}
				byteBuffer.clear();
			}
			System.out.println(sb.toString());
			return null;
		}
		
		
		
	}

}
